package training.list.refimpl;

import training.list.ListNode;
import training.list.ReverseKGroup;

public class ReverseKGroupSolution implements ReverseKGroup {

    @Override
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null) {
            return null;
        }
        ListNode kNode = head;
        for(int i=0; i<k;i++) {
            if(kNode == null) {
                return head;
            }
            kNode = kNode.next;
        }

        ListNode prev = null;
        ListNode cur = head;
        for(int i=0; i<k; i++) {
            ListNode temp = cur.next;
            cur.next = prev;
            prev = cur;
            cur = temp;
        }
        head.next = reverseKGroup(kNode, k);

        return prev;
    }

}
